package com.example.demo.demos.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.IntStream;

@RequestMapping("/rpc")
@RestController
@Slf4j
public class Hello {
    @Autowired
    private IpConfig ipConfig;
    private final RestTemplate restTemplate;
    private ThreadLocal<Integer> currentUser = ThreadLocal.withInitial(() ->null);


    public Hello(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping("/lift/enter")
        private ResponseVo hello(@RequestBody AgvLiftStorageLocationDto dto){
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);

        final AtomicInteger atomicCount = new AtomicInteger();
        int count = atomicCount.incrementAndGet(); // 原子地增加计数器并获取新值
        String liftTaskId = String.valueOf(count);

        log.info("车号id：{}，电梯号：{}，电梯储位：{}",dto.getAgvId(),dto.getLiftCode(),dto.getStoragePoint());
        System.out.println("tskIp："+ ipConfig.getIp());
        System.out.println("tskPort："+ ipConfig.getPort());

        System.out.println("chufajiekou:"+ liftTaskId);
        return responseVo;
    }
    @PostMapping("/lift/arrive")
    private ResponseVo arrive(@RequestBody AgvLiftEndFloorDto dto){
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);
        log.info("车号id：{}，电梯号：{}，电梯到达最终楼层：{}",dto.getAgvId(),dto.getLiftCode(),dto.getArriveFloor());
        return responseVo;
    }

    @PostMapping("/fire/control/on")
    private ResponseVo fire(@RequestBody List<LiftFirefightingOpenDto> liftFirefightingOpenDto){
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);
        log.info("请求参数:{}",liftFirefightingOpenDto);
        return responseVo;
    }

    @PostMapping("/fire/control/arrive")
    private ResponseVo fire(@RequestBody LiftCode liftCode){
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);
        log.info("请求参数:{}",liftCode);
        return responseVo;
    }
    @GetMapping("/fire/control/off")
    private ResponseVo fire(){
        ResponseVo responseVo = new ResponseVo();
        responseVo.setReturnCode(1);
        log.info("消防模式关闭");
        return responseVo;
    }

    @GetMapping("/fire/test")
    private void test(){
        GlobalMapProvider.putToGlobalMap("1","1");
        log.info("agv模式开启");
    }
    @GetMapping("/fire/test1/{id}")
    private void test1(@PathVariable("id") Integer id){
        log.info("前端传参:{}",id);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSSS");
        String format = simpleDateFormat.format(System.currentTimeMillis());
       log.info("id:{}",format);
        GlobalMapProvider.putToGlobalMap("1","0");
        log.info("手动模式开启");
    }
    @GetMapping("/wrong")
    public Map wrong(@RequestParam("userId") Integer userId){
        String before = Thread.currentThread().getName()+":"+ currentUser.get();
        currentUser.set(userId);
        HashMap<String, String> hashMap;
        try {
            log.info("===============");
            String after = Thread.currentThread().getName()+":"+ currentUser.get();
            hashMap = new HashMap<>();
            hashMap.put("before",before);
            hashMap.put("after",after);
        } finally {
            currentUser.remove();
        }
        return hashMap;
    }
    @GetMapping("/right")
    public int right() throws InterruptedException {
        //计数器
        AtomicInteger atomicInteger = new AtomicInteger();
        //线程池，2核心，5最大，10队列
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                2,5,
                5, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
        IntStream.rangeClosed(1,20).forEach(i -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int id = atomicInteger.incrementAndGet();
            try {
                threadPoolExecutor.submit(() -> {
                    try {
                        TimeUnit.SECONDS.sleep(10);
                    } catch (InterruptedException e) {
                    }
                    log.info("{}，finished", id);
                });
            } catch (Exception e) {
                log.error("error submitting task {}",id,e);
                atomicInteger.decrementAndGet();
            }
        });
        TimeUnit.SECONDS.sleep(60);
//        threadPoolExecutor.shutdown();
        return atomicInteger.intValue();
    }
    @GetMapping("/fire/downloadExcel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition", "attachment; filename=\"poiexcel03.xls\"");

        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("第一个工作表");

        // 获取调色板并修改颜色
        HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook;
        HSSFPalette palette = hssfWorkbook.getCustomPalette();

        // 定义一个灰色 (192, 192, 192)
        palette.setColorAtIndex((short) 10, (byte) 192, (byte) 192, (byte) 192);

        // 创建灰色背景的单元格样式
        CellStyle grayStyle = workbook.createCellStyle();
        grayStyle.setFillForegroundColor((short) 10); // 使用自定义颜色的索引
        grayStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 填充模式

        // 创建行
        Row row1 = sheet.createRow(0); // 第一行
//        Row row2 = sheet.createRow(1); // 第二行
//        Row row3 = sheet.createRow(2); // 第三行

        // 为第一行的单元格设置样式
        for (int i = 0; i < 7; i++) {
            Cell cell = row1.createCell(i);
            cell.setCellStyle(grayStyle);
        }

        // 设置第一行单元格的值
        row1.getCell(0).setCellValue("入库单号");
        row1.getCell(1).setCellValue("工单类型");
        row1.getCell(2).setCellValue("状态");
        row1.getCell(3).setCellValue("下发时间");
        row1.getCell(4).setCellValue("开始时间");

        // 获取当前时间并格式化
        String curdate = "2024-08-22 16:04:34"; // 示例时间
        row1.getCell(5).setCellValue(curdate);
        row1.getCell(6).setCellValue("结束时间");
        ArrayList<User> users = new ArrayList<>();
        User user = new User("张三",18);
        User user1 = new User("张三",17);
        User user2 = new User("张三",19);
        User user3 = new User("王三",21);
        User user4 = new User("张三",20);
        users.add(user);
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
//        row2.createCell(0).setCellValue("dfas"); q
        for (int i = 0; i < users.size(); i++) {
            Row row = sheet.createRow(i + 1);
            User user5 = users.get(i);
            row.createCell(0).setCellValue(user5.getName());
            row.createCell(1).setCellValue(user5.getAge());
        }
        // 写入响应输出流
        try (OutputStream out = response.getOutputStream()) {
            workbook.write(out);
        } finally {
            workbook.close();
        }
    }
}
